package com.baizhou.honglv.service.impl;

import com.baizhou.honglv.bean.exception.SysException;
import com.baizhou.honglv.bean.redis.RedisRepository;
import com.baizhou.honglv.bean.util.SendNoteUtil;
import com.baizhou.honglv.bean.util.TokenUtil;
import com.baizhou.honglv.dto.LoginSuccessDto;
import com.baizhou.honglv.dto.RegisterSuccessDto;
import com.baizhou.honglv.dto.TokenInfo;
import com.baizhou.honglv.entity.User;
import com.baizhou.honglv.form.ChangeForm;
import com.baizhou.honglv.form.LoginForm;
import com.baizhou.honglv.form.PhoneNumberForm;
import com.baizhou.honglv.form.VerificationForm;
import com.baizhou.honglv.mapper.UserMapper;
import com.baizhou.honglv.service.UserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wanghaipeng
 * @since 2021-07-14
 */
@Slf4j
@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisRepository redisRepository;

    /**
     * 添加一个用户
     *
     * @param user
     */
    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    @Override
    public User selectByid(User user) {
        return userMapper.selectById(user.getId());
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectList(new QueryWrapper<>(null));
    }

    @Override
    public void delete(User user){
        userMapper.deleteById(user.getId());
    }

    @Override
    public LoginSuccessDto login(LoginForm loginForm) {
        if (loginForm.getPhoneNumber () == null) {
            throw new SysException("未传递手机号");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone_number",loginForm.getPhoneNumber ());

        User userEntity = userMapper.selectOne((Wrapper<User>) queryWrapper);
        if (null == userEntity) {
            log.info("用户不存在！");
            throw new SysException("用户不存在！");
        } else if (!userEntity.getPassword ().equals(loginForm.getPassword ())) {
            log.info("手机号与密码不匹配错误");
            throw new SysException("手机号与密码不匹配不匹配错误");
        } else {
            //删除旧的token
            deleteToken(userEntity.getId());
            //得到一个accessToken，生成tokenInfo
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setAccessToken(TokenUtil.getToken());  //创建并获取一个token
            tokenInfo.setUserId(userEntity.getId());    //获取userid
            LoginSuccessDto loginSuccessDto = new LoginSuccessDto();
            loginSuccessDto.setAccessToken(tokenInfo.getAccessToken());
            //保存这个用户和token信息
            redisRepository.saveAccessToken(tokenInfo);
            redisRepository.saveLoginAccessToken(tokenInfo);
            redisRepository.saveLoginTime(userEntity.getId(),
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            System.out.println("token信息:" + tokenInfo.getAccessToken());
            return loginSuccessDto;
        }
    }

    @Override
    public void changePassword(ChangeForm changeForm){
        if (changeForm.getNewPassword () == null || changeForm.getNewPasswordAgain ()==null) {
            throw new SysException ("未传递新密码");
        }

        QueryWrapper queryWrapper = new QueryWrapper ();
        queryWrapper.eq ("id", changeForm.getUserId ());

        User userEntity = new User ();
        userEntity.setPassword (changeForm.getNewPasswordAgain ());

        if (!(userMapper.selectById (changeForm.getUserId ()) ==null)) {
            userMapper.update (userEntity,queryWrapper);
            deleteToken(userEntity.getId());
        }else{
            log.info ("用户未注册");
            throw new SysException ("用户未注册");
        }
    }

    @Override
    public RegisterSuccessDto register(VerificationForm verificationForm)  {

        if (verificationForm.getPhoneNumber ()==null|| verificationForm.getPhoneNumber ().equals ("")){
            throw new SysException ("未传递手机号");
        }else if (verificationForm.getNote ()==null|| verificationForm.getNote ().equals ("")) {
            throw new SysException ("未传递验证码");
        }else {

            QueryWrapper queryWrapper = new QueryWrapper ();
            queryWrapper.eq ("phone_number", verificationForm.getPhoneNumber ());

            User user = userMapper.selectOne (queryWrapper);

            if (user != null) {
                log.info ("该用户已注册");
                throw new SysException ("该用户已注册");
            }
            UserService userService = new UserServiceImpl ();

            if (userService.verification (verificationForm)) {
                String tempPassword = TokenUtil.getToken ();
                User userEntity = new User ();
                userEntity.setPhoneNumber (verificationForm.getPhoneNumber ());
                userEntity.setPassword (tempPassword);
                userMapper.insert(userEntity);
                TokenInfo tokenInfo = new TokenInfo();
                tokenInfo.setAccessToken(tempPassword);  //创建并获取一个token
                tokenInfo.setUserId(userEntity.getId());
                redisRepository.saveRegisterAccessToken (tokenInfo);
                RegisterSuccessDto registerSuccessDto = new RegisterSuccessDto ();
                registerSuccessDto.setAccessToken (tokenInfo.getAccessToken ());
                return registerSuccessDto;
            }else {
                throw new SysException ("验证码错误");
            }
        }
    }

    /**
     * //修改密码或异地登录删除旧的token
     * @param userId
     */
    @Override
    public void deleteToken(String userId){
        String oldToken = redisRepository.selectLoginAccessToken(userId);
        if(null != oldToken){
            redisRepository.deleteAccessToken(oldToken);
            redisRepository.deleteLoginAccessToken(userId);
        }
        String loginTime = redisRepository.selectLoginTimeByUser(userId);
        if(loginTime!=null){
            redisRepository.deleteLoginTime(userId);
        }
    }

    @Override
    public boolean SendNote(PhoneNumberForm phoneNumberForm){
        SendNoteUtil sendNoteUtil = new SendNoteUtil ();
        sendNoteUtil.sendNoteMessgae (phoneNumberForm.getPhoneNumber (),"模板");
        String phone = redisRepository.selectMessageCodeByPhone (phoneNumberForm.getPhoneNumber ());
        return phone != null && !phone.equals ("");
    }

    @Override
    public boolean verification(VerificationForm verificationForm) {
//        String code = redisRepository.selectMessageCodeByPhone (verificationForm.getPhoneNumber ());
//        return code != null && !code.equals ("");
        return true;
    }
}
